<?php
namespace app\middleware;

use app\common\traits\ApiTrait;
use ReflectionClass;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use think\facade\Db;
use Tinywan\Jwt\JwtToken;

class UserAuthCheck implements MiddlewareInterface
{
    use ApiTrait;

    public function process(Request $request, callable $handler) : Response
    {
        // 通过反射获取控制器哪些方法不需要登录
        $controller = new ReflectionClass($request->controller);
        $noNeedLogin = $controller->getDefaultProperties()['noNeedLogin'] ?? [];

        // 访问的方法需要登录
        if (!in_array($request->action, $noNeedLogin)) {
            try {
                $userToken = JwtToken::getExtend();
                if (empty(Db::name('user')->where(['id' => $userToken['id']])->find())) {
                    return $this->reError('未登录', true, 401);
                }
            } catch (\Exception $e) {
                return $this->reError('未登录', true, 401);
            }
        }
        return $handler($request);
    }
}